"""
语音MCP服务器实现
获取语音输入状态、语音输入内容
"""

from typing import Dict, Any, Optional, List
from mcp.server.fastmcp import FastMCP
from sensors.voice_sensor import VoiceSensor, VoiceEvent, VoiceEventType
import os


class VoiceServer(FastMCP):
    """语音传感器服务器类"""

    def __init__(self):
        """初始化语音传感器服务器"""
        super().__init__("voice_server")

        # 初始化语音传感器
        self.sensor = VoiceSensor(
            config={
                "access_key": os.environ.get("PICOVOICE_ACCESS_KEY"),
                "wake_word": "hey siri",
                "vad_aggressiveness": 2,
                "sample_rate": 16000,
                "frame_duration_ms": 30,
                "input_device": "plughw:2,0",
                "max_silence_seconds": 4,
                "min_speech_seconds": 0.5,
                "save_audio": True,
                "audio_dir": "audio",
            },
            callback=self._on_voice_event,
        )

        # 注册工具
        self._register_tools()

    def _on_voice_event(self, event: VoiceEvent):
        """语音事件回调函数"""
        try:
            if event.type == VoiceEventType.WAKE_WORD:
                print("检测到唤醒词")
            elif event.type == VoiceEventType.SPEECH_START:
                print("检测到语音开始")
            elif event.type == VoiceEventType.SPEECH_DATA:
                print(f"收到语音数据，长度: {len(event.data)} 字节")
            elif event.type == VoiceEventType.SPEECH_END:
                print("语音结束")
            elif event.type == VoiceEventType.ERROR:
                print(f"发生错误: {event.error}")
        except Exception as e:
            print(f"处理语音事件时出错: {e}")

    def _register_tools(self):
        """注册所有语音传感器工具"""

        @self.tool()
        async def start_listening() -> Dict[str, Any]:
            """开始监听语音

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                self.sensor.start()
                return {"status": "success", "message": "Started listening"}
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def stop_listening() -> Dict[str, Any]:
            """停止监听语音

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                self.sensor.stop()
                return {"status": "success", "message": "Stopped listening"}
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def get_event_history(limit: Optional[int] = None) -> Dict[str, Any]:
            """获取事件历史记录

            Args:
                limit: 返回的最大事件数量

            Returns:
                Dict[str, Any]: 事件历史记录
            """
            try:
                events = self.sensor.get_event_history(limit)
                return {
                    "status": "success",
                    "data": [
                        {
                            "type": event.type.value,
                            "timestamp": event.timestamp,
                            "data_length": len(event.data) if event.data else 0,
                            "error": event.error,
                        }
                        for event in events
                    ],
                }
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def clear_event_history() -> Dict[str, Any]:
            """清除事件历史记录

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                self.sensor.clear_event_history()
                return {"status": "success", "message": "Cleared event history"}
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def set_wake_word(wake_word: str) -> Dict[str, Any]:
            """设置唤醒词

            Args:
                wake_word: 新的唤醒词

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                self.sensor.wake_word = wake_word
                return {"status": "success", "message": f"Set wake word to {wake_word}"}
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def set_vad_aggressiveness(aggressiveness: int) -> Dict[str, Any]:
            """设置VAD灵敏度

            Args:
                aggressiveness: VAD灵敏度(0-3)

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                if not 0 <= aggressiveness <= 3:
                    return {
                        "status": "error",
                        "message": "VAD aggressiveness must be between 0 and 3",
                    }

                self.sensor.vad_aggressiveness = aggressiveness
                self.sensor._init_vad()

                return {
                    "status": "success",
                    "message": f"Set VAD aggressiveness to {aggressiveness}",
                }
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def set_silence_threshold(seconds: float) -> Dict[str, Any]:
            """设置静音阈值

            Args:
                seconds: 静音阈值(秒)

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                self.sensor.max_silence_seconds = seconds
                return {
                    "status": "success",
                    "message": f"Set silence threshold to {seconds} seconds",
                }
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def set_min_speech_duration(seconds: float) -> Dict[str, Any]:
            """设置最小语音持续时间

            Args:
                seconds: 最小语音持续时间(秒)

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                self.sensor.min_speech_seconds = seconds
                self.sensor.min_speech_frames = int(
                    seconds * 1000 / self.sensor.frame_duration_ms
                )
                return {
                    "status": "success",
                    "message": f"Set minimum speech duration to {seconds} seconds",
                }
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def get_sensor_status() -> Dict[str, Any]:
            """获取传感器状态

            Returns:
                Dict[str, Any]: 传感器状态
            """
            try:
                return {
                    "status": "success",
                    "data": {
                        "is_listening": self.sensor.is_listening,
                        "is_recording": self.sensor.is_recording,
                        "wake_word": self.sensor.wake_word,
                        "vad_aggressiveness": self.sensor.vad_aggressiveness,
                        "max_silence_seconds": self.sensor.max_silence_seconds,
                        "min_speech_seconds": self.sensor.min_speech_seconds,
                        "sample_rate": self.sensor.sample_rate,
                        "frame_duration_ms": self.sensor.frame_duration_ms,
                        "input_device": self.sensor.input_device,
                        "save_audio": self.sensor.save_audio,
                        "audio_dir": self.sensor.audio_dir,
                    },
                }
            except Exception as e:
                return {"status": "error", "message": str(e)}
